<template>
	<view>
		<view class="uni-header">
			<view class="uni-group hide-on-phone">
				<view class="uni-title">报名管理</view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<uni-data-select style="width: 500rpx;" v-model="selectValue" placeholder="请选择比赛"
					:localdata="rangeSelect" @change="changeSelect"></uni-data-select>
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<!-- #ifdef H5 -->
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
				<!-- #endif -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" collection="order" page-data="replace" :where="where" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" @load="onqueryload">
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe>
					<uni-tr>
						<uni-th align="center">比赛名称</uni-th>
						<uni-th align="center">比赛图片</uni-th>
						<uni-th align="center">组别</uni-th>
						<uni-th align="center">报名单号</uni-th>
						<uni-th align="center">报名人</uni-th>
						<uni-th align="center">性别</uni-th>
						<uni-th align="center">年龄</uni-th>
						<uni-th align="center">报名人联系方式</uni-th>
						<uni-th align="center">支付时间</uni-th>
						<uni-th align="center">报名状态</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in expData" :key="index">
						<uni-td align="center" width="204">{{item.goodsName}}</uni-td>
						<uni-td align="center" width="204">
							<template>
								<image :src="item.photo_url" style="width: 120rpx;height: 120rpx;border-radius: 10rpx;">
								</image>
							</template>
						</uni-td>
						<uni-td align="center" width="204">
							<template>
								<view v-if="item.uLevel== 0">
									其他
								</view>
								<view v-if="item.uLevel== 6" style="color: #82848a;">U6</view>
								<view v-if="item.uLevel== 6" style="color: #82848a;">U8</view>
								<view v-if="item.uLevel== 6" style="color: #82848a;">U10</view>
								<view v-if="item.uLevel== 6" style="color: #82848a;">U12</view>
							</template>
						</uni-td>
						<uni-td align="center">{{item.outTradeNo}}</uni-td>
						<uni-td align="center">{{item.username}}</uni-td>
						<uni-td align="center">
							<view v-if="item.sex == 1">男</view>
							<view v-if="item.sex == 2">女</view>
							<view v-if="!item.sex">未知</view>
						</uni-td>
						<uni-td align="center">{{item.age}}</uni-td>
						<uni-td align="center">{{item.userphone}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :date="item.pay_date"></uni-dateformat></uni-td>
						<uni-td align="center">
							<template>
								<uni-tag v-if="item.status == 0" type='warning' text="待支付"></uni-tag>
								<uni-tag v-if="item.status == 1" type="success" text="已支付"></uni-tag>
								<uni-tag v-if="item.status == 3" type="default" text="已取消"></uni-tag>
								<uni-tag v-if="item.status == 4" type="error" text="申请退款"></uni-tag>
							</template>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button v-if="item.status == 4" @click="tipsClick(item)" class="uni-button" size="mini"
									type="primary">退款</button>
								<button @click="confirmDelete(item)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<picker class="select-picker" mode="selector" :value="pageSizeIndex" :range="pageSizeOption"
						@change="changeSize">
						<button type="default" size="mini" :plain="true">
							<text>{{pageSizeOption[pageSizeIndex]}} 条/页</text>
							<uni-icons class="select-picker-icon" type="arrowdown" size="12" color="#999"></uni-icons>
						</button>
					</picker>
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
		<uni-pay ref="pay"></uni-pay>
	</view>
</template>

<script>
	import {
		enumConverter
	} from '../../../js_sdk/validator/zixun.js'
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '_id desc' // 排序字段
	const dbSearchFields = ['goodsName', 'outTradeNo', 'username', 'age', 'userphone'] // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				selectValue: 0,
				rangeSelect: [],
				query: '',
				where: '',
				orderby: dbOrderBy,
				options: {
					pageSize,
					pageCurrent,
					...enumConverter
				},
				pagination: {
					count: 0,
					size: 20,
					current: 1
				},
				selectedIndexs: [], //批量选中的项
				pageSizeIndex: 0,
				pageSizeOption: [20, 50, 100, 500],
				expData: [],
				exportExcel: {
					"filename": "报名数据.xls",
					"type": "xls",
					"fields": {
						"比赛名称": "goodsName",
						"报名单号": "outTradeNo",
						"报名费用": "totalFee",
						"报名人": "username",
						"报名人openId": "openId",
						"性别": "sex",
						"年龄": "age",
						"联系电话": "userphone",
						"组别": "uLevel",
						"报名状态": "status",
						"支付时间": "payDate"
					}
				},
				exportExcelData: []
			}
		},
		watch: {
			pageSizeIndex: {
				immediate: true,
				handler(val, old) {
					this.options.pageSize = this.pageSizeOption[val]
					this.options.pageCurrent = 1
				}
			}
		},
		onLoad() {
			this.getSelect()
		},
		onShow() {
			this.$nextTick(() => {
				this.$refs.udb.loadData()
			}, 500)
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			//获取比赛列表
			getSelect() {
				uniCloud.callFunction({
					name: 'compadmin',
					data: {
						type: 'get'
					},
					success: res => {
						this.rangeSelect = res.result.data.map(item => {
							return {
								text: item.title,
								value: item._id
							}
						})

						console.log('sss', this.rangeSelect)
					}
				})
			},
			// 选择比赛
			changeSelect(e) {
				console.log(e)
				if (e == '') {
					this.query = ''
					return
				}
				let obj = this.rangeSelect.find(item => item.value == e)
				this.query = obj.text
				console.log(obj)
				//	this.query = e
			},
			onqueryload(data) {
				data.forEach(item => {
					item.payDate = this.formatDate(item.pay_date)
					if (item.userAge) {
						var currentYear = new Date().getFullYear();
						item.age = currentYear - item.userAge.split('-')[0]
					} else {
						item.age = 0
					}

				})
				this.exportExcelData = data
				this.expData = data
			},
			//格式化时间
			formatDate(date) {
				var date = new Date(date);
				var YY = date.getFullYear() + '-';
				var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
				var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
				var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
				return YY + MM + DD + " " + hh + mm + ss;
			},

			changeSize(e) {
				this.pageSizeIndex = e.detail.value
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search(e) {
				const newWhere = this.getWhere()
				const isSameWhere = newWhere === this.where
				this.where = newWhere
				if (isSameWhere) { // 相同条件时，手动强制刷新
					this.loadData()
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.options.pageCurrent = e.current
			},
			navigateTo(url, clear) { // clear 表示刷新列表时是否清除当前页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(item) {
				uni.showModal({
					title: '提示',
					content: '确定要删除此报名数据？',
					success: Res => {
						if (Res.confirm) {
							uniCloud.callFunction({
								name: 'orderadmin',
								data: {
									type: 'del',
									id: item._id
								},
								success: res => {
									uni.showToast({
										title: '删除成功',
										icon: 'none'
									})
									this.$refs.udb.loadData()
								}
							})
						}
					}

				})

			},
			tipsClick(item) {
				console.log('item==>', item)
				uni.showModal({
					title: '提示',
					content: '确定要退款？',
					success: async Res => {
						if (Res.confirm) {
							let res = await this.$refs.pay.refund({
								out_trade_no: item.outTradeNo, // 插件支付单号
							});
							if (res) {
								item.status = 3
								uniCloud.callFunction({
									name: 'update',
									data: {
										dbName: 'order',
										datas: item
									},
									success: res => {
										uni.showToast({
											title: '退款成功！',
											icon: 'none'
										})
										this.$refs.udb.loadData()
									}
								})
							}
							// uniCloud.callFunction({
							// 	name: 'orderadmin',
							// 	data: {
							// 		type: 'refund',
							// 		id: item._id,
							// 		orderNo: item.outTradeNo
							// 	},
							// 	success: res => {
							// 		uni.showToast({
							// 			title: '操作成功',
							// 			icon: 'none'
							// 		})
							// 		this.onqueryload()
							// 	}
							// })
						}
					}

				})
			},
			parseUserStatus(status) {
				if (status === 0) {
					return '启用'
				} else if (status === 1) {
					return '禁用'
				} else if (status === 2) {
					return '审核中'
				} else if (status === 3) {
					return '审核拒绝'
				} else {
					return '启用'
				}
			}
		}
	}
</script>
<style>
	/* #ifndef H5 */
	page {
		padding-top: 85px;
	}

	/* #endif */
</style>